package com.zang.server.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.zang.server.annotation.OptLog;
import com.zang.server.pojo.*;
import com.zang.server.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.List;

import static com.zang.server.constanct.OptTypeConst.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zang
 * @since 2021-12-28
 */
@Api(tags = "员工管理模块")
@RestController
@RequestMapping("/employee/basic")
public class EmployeeController {
    @Autowired
    private IEmployeeService iEmployeeService;
    @Autowired
    private IPoliticsStatusService iPoliticsStatusService;
    @Autowired
    private IJoblevelService iJoblevelService;
    @Autowired
    private INationService iNationService;
    @Autowired
    private IPositionService iPositionService;
    @Autowired
    private IDepartmentService iDepartmentService;
    @ApiOperation(value = "查询所有员工(分页)" )
    @GetMapping("/")
    public RespPageBean getEmployee(@RequestParam(defaultValue = "1") Integer currentPage,
                                    @RequestParam(defaultValue = "10") Integer size,
                                    Employee employee,
                                    LocalDate[] beginDateScope
                                    ){
        return iEmployeeService.getEmployeeByPage(currentPage,size,employee,beginDateScope);
    }
    @ApiOperation(value = "获取所有政治面貌")
    @GetMapping("/politicsstatus")
    public List<PoliticsStatus> getAllPoliticsStatus(){
        return iPoliticsStatusService.list();
    }
    @ApiOperation(value = "获取所有职称")
    @GetMapping("/joblevels")
    public List<Joblevel> getAllJoblevel(){
        return iJoblevelService.list();
    }
    @ApiOperation(value = "获取所有民族")
    @GetMapping("/nations")
    public List<Nation> getAllNations(){
        return iNationService.list();
    }

    @ApiOperation(value = "获取所有的职位")
    @GetMapping("/positions")
    public List<Position> getAllPositions(){
       return iPositionService.list();
    }
    @ApiOperation(value = "获取所有部门")
    @GetMapping("/deps")
    public List<Department> getAllDepartment(){
        return iDepartmentService.getAllDepartments();
    }
    @ApiOperation(value = "获取工号")
    @GetMapping("/maxWorkID")
    public RespBean maxWorkID(){
        return iEmployeeService.maxWorkID();
    }
    @OptLog(optType = SAVE)
    @ApiOperation(value = "添加员工")
    @PostMapping("/")
    public RespBean addEmp(@RequestBody Employee employee){
       return iEmployeeService.addEmp(employee);
    }
    @OptLog(optType = UPDATE)
    @ApiOperation(value = "更新员工")
    @PutMapping("/")
    public RespBean updateEmp(@RequestBody Employee employee){
        if (iEmployeeService.updateById(employee)){
            return RespBean.success("成功更新员工信息!");
        }
        return RespBean.error("更新员工信息失败!");
    }
    @OptLog(optType = REMOVE)
    @ApiOperation(value = "删除员工")
    @DeleteMapping("/{id}")
    public RespBean deleteEmp(@PathVariable("id") Integer id){
        if (iEmployeeService.removeById(id)){
            return RespBean.success("员工成功删除!");
        }
        return RespBean.error("员工删除失败!");
    }
    @OptLog(optType = download)
    @ApiOperation(value = "导出员工数据")
    @GetMapping(value = "export",produces = "application/octet-stream")
    public void exportEmployee(HttpServletResponse response){
        List<Employee> employee = iEmployeeService.getEmployee(null);
        ExportParams exportParams = new ExportParams("员工表", "员工表", ExcelType.HSSF);
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, Employee.class, employee);
        ServletOutputStream outputStream=null;
        try {
            //用流的形式传输
            response.setHeader("content-type","application/octet-stream");
            //防止中文乱码
            response.setHeader("content-disposition","attachment;filename="+ URLEncoder.encode("员工表.xls","UTF-8"));
          outputStream = response.getOutputStream();
          workbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (null!=outputStream){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    @OptLog(optType = UPLOAD)
    @ApiOperation(value = "导入员工数据")
    @PostMapping("/import")
    public RespBean importEmployee(MultipartFile file){
        ImportParams params = new ImportParams();
        //去掉标题行
        params.setTitleRows(1);
        List<Nation> nationList = iNationService.list();
        List<PoliticsStatus> politicsStatusList = iPoliticsStatusService.list();
        List<Department> departmentList = iDepartmentService.list();
        List<Joblevel> joblevelList = iJoblevelService.list();
        List<Position> positionList = iPositionService.list();
        try {
            List<Employee> list = ExcelImportUtil.importExcel(file.getInputStream(), Employee.class, params);
            list.forEach(employee -> {
                /**
                 *      因为我们的数据库里存的是他们的name所有我们重写了equals和hashcode，这样我们就可以比较对象，
                 *      首先我们通过name比较得到下标然后通过下标得到对象，此时对象就是有id和name的，通过对象得到id再将id存入就ok
                 */
                //民族id
                employee.setNationId(nationList.get(nationList.indexOf(new Nation(employee.getNation().getName()))).getId());
                //政治面貌id
                employee.setPoliticId( politicsStatusList.get(politicsStatusList.indexOf(new PoliticsStatus(employee.getPoliticsStatus().getName()))).getId());
                //部门id
                employee.setDepartmentId(departmentList.get(departmentList.indexOf(new Department(employee.getDepartment().getName()))).getId()) ;
                //职称id
                employee.setJobLevelId(joblevelList.get(joblevelList.indexOf(new Joblevel(employee.getJoblevel().getName()))).getId());
                //职位id
                employee.setPosId(positionList.get(positionList.indexOf( new Position(employee.getPosition().getName()))).getId());
            });
            if (iEmployeeService.saveBatch(list)){
                return RespBean.success("导入成功!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RespBean.error("导入失败!");
    }
}
